using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace SharePointFarmInfoTimerJob.Features.SharePointFarmInfoTimerJob_Feature
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("b7c3d893-2290-458e-bd1e-99f6796e5b99")]
    public class SharePointFarmInfoTimerJob_FeatureEventReceiver : SPFeatureReceiver
    {
        /// <summary>
        /// Feature Activated Event
        /// </summary>
        /// <param name="properties">SPFeatureReceiverProperties</param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //This is a site level feature
            //Retrive the SPSite
            SPSite site = properties.Feature.Parent as SPSite;

            if (site == null)
            {
                return;
            }

            // make sure the job isn't already registered
            foreach (SPJobDefinition jobDef in site.WebApplication.JobDefinitions)
            {
                if (jobDef.Name == Global.jobName)
                {
                    jobDef.Delete();
                }
            }

            //Schedule the job to run every 30minutes by default
            SharePointFarmInfoTimerJob job = new SharePointFarmInfoTimerJob(site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 30;

            job.Schedule = schedule;
            job.Update();
        }


        /// <summary>
        /// Feature Deactivating
        /// </summary>
        /// <param name="properties">SPFeatureReceiverProperties</param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            if (site == null)
            {
                return;
            }

            // Remove the job
            foreach (SPJobDefinition jobDef in site.WebApplication.JobDefinitions)
            {
                if (jobDef.Name == Global.jobName)
                {
                    jobDef.Delete();
                }
            }
        }        
    }
}
